package com.it.travel.service.admin.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.it.travel.dao.PermissionMapper;
import com.it.travel.dao.RoleMapper;
import com.it.travel.dao.RolePermissionMapper;
import com.it.travel.dao.UserRoleMapper;
import com.it.travel.dto.admin.AdminRoleDTO;
import com.it.travel.pojo.Permission;
import com.it.travel.pojo.Role;
import com.it.travel.pojo.RolePermission;
import com.it.travel.pojo.UserRole;
import com.it.travel.service.admin.AdminRoleService;
import com.it.travel.vo.Params.PageParams;
import com.it.travel.vo.Params.admin.AdminRoleParams;
import com.it.travel.vo.Params.admin.AdminRolePermissionAddParams;
import com.it.travel.vo.Params.admin.AdminRoleUpdateParams;
import com.it.travel.vo.Result;
import com.it.travel.vo.admin.AdminPermissionTreeVO;
import com.it.travel.vo.admin.AdminRoleVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class AdminRoleServiceImpl implements AdminRoleService {
    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public Result<?> getInfoPage(PageParams pageParams) {
        pageParams.setIndex((pageParams.getIndex() - 1) * pageParams.getSize());
        LambdaQueryWrapper<Role> wrapper = Wrappers.lambdaQuery();
        Integer total = roleMapper.selectCount(null);
        List<AdminRoleDTO> list = roleMapper.queryRole(pageParams.getIndex(), pageParams.getSize());
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<AdminRoleVO> list1 = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-mm HH:mm:ss");
        for (AdminRoleDTO adminRoleDTO : list) {
            AdminRoleVO adminRoleVO = new AdminRoleVO();
            BeanUtil.copyProperties(adminRoleDTO, adminRoleVO);
            String format = simpleDateFormat.format(new Date(adminRoleDTO.getCreateTime()));
            adminRoleVO.setFormatTime(format);
            list1.add(adminRoleVO);
        }
        map.put("roleList", list1);
        map.put("total", total);
        return Result.success(map, "获取数据成功");
    }

    @Override
    @Transactional
    public Result<?> delete(Integer id) {  // 由于没有外键，所以在这里进行应用层面的级联删除
        int i1 = rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", id));
        int i2 = userRoleMapper.delete(new QueryWrapper<UserRole>().eq("role_id", id));
        int i = roleMapper.deleteById(id);
        if (i > 0 && i1 > 0 && i2 > 0) {
            return Result.success(null, "删除成功");
        }
        return Result.error(null, "删除失败");

    }

    @Override
    public Result<?> save(AdminRoleParams adminProductParams) {
        Role role = new Role();
        BeanUtil.copyProperties(adminProductParams, role);
        role.setCreateTime(System.currentTimeMillis());
        role.setUpdateTime(System.currentTimeMillis());
        int i = roleMapper.insert(role);
        if (i > 0) {
            return Result.success(null, "新增成功");
        }
        return Result.error(null, "新增失败");
    }

    @Override
    public Result<?> update(AdminRoleUpdateParams adminRoleUpdateParams) {
        Role role = new Role();
        BeanUtil.copyProperties(adminRoleUpdateParams, role);
        role.setCreateTime(System.currentTimeMillis());
        role.setUpdateTime(System.currentTimeMillis());
        int i = roleMapper.updateById(role);
        if (i > 0) {
            return Result.success(null, "修改成功");
        }
        return Result.error(null, "修改失败");
    }

    @Override
    public Result<?> getPermissionInfo(Integer roleId) { // 后台角色列表分配权限的数据
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        wrapper.select("id", "permission_name", "parent_id");
        List<Integer> permissionIds = roleMapper.queryPermissionIByRoleId(roleId);

//        roleMapper.queryPermissionIByRoleId(roleId);
        List<Permission> permissions = permissionMapper.selectList(wrapper);
        List<Permission> permissionList = getPermissionList(permissions, 0);
        List<Permission> list = new ArrayList<>();
        for (Permission permission : permissionList) {
            if (permission.getParentId() == 0) {
                list.add(permission);
            }
        }
        map.put("permissionList", list);
        map.put("permissionIds", permissionIds);
        return Result.success(map, "获取数据成功");
    }

    /**
     * 为角色分配对应的权限
     * 先根据角色id删除所有数据，再新增，因为有可能，之前选择的，又取消，应该做删除操作
     *
     * @param adminRolePermissionAddParams
     * @return
     */
    @Override
    public Result<?> savePermissionInfo(AdminRolePermissionAddParams adminRolePermissionAddParams) {
        List<Integer> permissionIds = adminRolePermissionAddParams.getPermissionIds();
        Integer roleId = adminRolePermissionAddParams.getRoleId();
//        先根据角色id 删除所有记录，然后再插入
        int role_id = rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        Integer count = 0;
        for (Integer permissionId : permissionIds) { // 如果为空就不行插入操作
            RolePermission rolePermission = new RolePermission();
            rolePermission.setCreateTime(System.currentTimeMillis());
            rolePermission.setUpdateTime(System.currentTimeMillis());
            rolePermission.setPermissionId(permissionId);
            rolePermission.setRoleId(roleId);
            int insert = rolePermissionMapper.insert(rolePermission);
            count++;
            if (count == permissionIds.size()) {
                return Result.success(null, "为角色分配权限成功");
            }
        }
        return Result.error(null, "为角色分配权限失败");
    }

    private List<Permission> getPermissionList(List<Permission> permissionList, Integer pid) {
        List<Permission> list = new ArrayList<>();
        for (Permission permission : permissionList) {
            if (pid.equals(0)) {
                list.add(permission);
                List<Permission> children = getPermissionList(permissionList, permission.getId());
                permission.setChildren(children);
            } else if (pid.equals(permission.getParentId())) {
                list.add(permission);
                List<Permission> children = getPermissionList(permissionList, permission.getId());
                permission.setChildren(children);
            }
        }
        return list;
    }
}
